/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.web.controller;

import cc.altius.domain.CustomUserDetails;
import cc.altius.model.Customer;
import cc.altius.model.Doctor;
import cc.altius.model.EmailTemplate;
import cc.altius.model.HealthSpringCenter;
import cc.altius.model.Hospital;
import cc.altius.model.ServiceDetails;
import cc.altius.service.CenterService;
import cc.altius.service.CustomerService;
import cc.altius.service.DoctorService;
import cc.altius.service.EmailService;
import cc.altius.service.HospitalService;
import cc.altius.service.ServiceDetailsService;
import cc.altius.utils.CommonUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author mudassar
 */
@Controller
public class EmailController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private CenterService centerService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private ServiceDetailsService serviceDetailsService;
    @Autowired
    private HospitalService hospitalService;

    @ModelAttribute("centerList")
    public List<HealthSpringCenter> populateCenterList() {
        return centerService.getCenterList();
    }

    @ModelAttribute("doctorList")
    public List<Doctor> populateDoctorList() {
        return doctorService.getDoctorList();
    }

    
    // FOR SENDING EMAIL TO DOCTOR FOLLOW-UP REMINDER
    @RequestMapping(value = "email/selectEmailTemplateForDoctor", method = RequestMethod.GET)
    public String showSmsGetPage(ModelMap modelMap) {
        //Customer customer = this.customerService.getCustomerDetails(customerId);
        List<EmailTemplate> emailTemplateList = this.emailService.getEmailTemplates();
        modelMap.addAttribute("emailTemplateList", emailTemplateList);
        //modelMap.addAttribute("customer", customer);
        return "email/selectEmailTemplate";
    }
    
    
    //step one
    @RequestMapping(value = "email/selectEmailTemplate", method = RequestMethod.GET)
    public String showSmsGetPage(@RequestParam(value = "customerId", required=false, defaultValue="0") int customerId,HttpServletRequest request ,ModelMap modelMap) {
        //int customerId= ServletRequestUtils.getIntParameter(request, "customerId", 0);
        Customer customer = this.customerService.getCustomerDetails(customerId);
        List<EmailTemplate> emailTemplateList = this.emailService.getEmailTemplates();
        modelMap.addAttribute("emailTemplateList", emailTemplateList);
        modelMap.addAttribute("customer", customer);
        return "email/selectEmailTemplate";
    }

    //step two
    @RequestMapping(value = {"email/selectEmailTemplate"}, method = RequestMethod.POST, params = "_stepTwo")
    public String sendEmailStepTwoPage(@RequestParam(value = "customerId",required=false) int customerId,
            @RequestParam(value = "emailTypeId", required = true) int emailTypeId,
            ModelMap modelMap) {
        Customer customer = this.customerService.getCustomerDetails(customerId);
        List<ServiceDetails> serviceDetailsList = this.serviceDetailsService.getListOfServices();
        modelMap.addAttribute("serviceDetailsList", serviceDetailsList);
        modelMap.addAttribute("customer", customer);
        modelMap.addAttribute("customerId", customerId);
        modelMap.addAttribute("emailTypeId", emailTypeId);
        return "email/sendEmail";
    }

    //finish
    @RequestMapping(value = {"email/selectEmailTemplate"}, method = RequestMethod.POST, params = "_finish")
    public String sendEmailStepThreePage(@RequestParam(value = "emailTypeId", required = true) int emailTypeId,
            @RequestParam(value = "customerId") int customerId,
            @RequestParam(value = "doctorId", defaultValue = "0") int doctorId,
            @RequestParam(value = "centerId", defaultValue = "0") int centerId,
            HttpServletRequest request,
            ModelMap modelMap) {
        
        String emailBody = ServletRequestUtils.getStringParameter(request, "emailBody", "");
        Customer customer = this.customerService.getCustomerDetails(customerId);
        //System.out.println("customer emailId :" + customer.getEmailId());
        String centreEmailId = this.centerService.getEmailIdOfCentre(centerId);
        String doctorEmailId = this.doctorService.getEmailIdOfDoctor(doctorId);
        if (!emailBody.isEmpty()) {
            if ((emailTypeId == 1 || emailTypeId == 3 || emailTypeId == 5 || emailTypeId == 6) && customer.getEmailId() == null) {
                return "redirect:/customer/editCustomer.htm?customerId=" + customerId + "&msg=msg.emailIdNotPresent";
            } else if ((emailTypeId == 1 || emailTypeId == 3 || emailTypeId == 5 || emailTypeId == 6) && !CommonUtils.isValidEmailId(customer.getEmailId())) {
                System.out.println("inside not valid emailID");
                return "redirect:/customer/editCustomer.htm?customerId=" + customerId + "&msg=msg.emailIdNotValid";
            } else if (emailTypeId == 2 && !CommonUtils.isValidEmailId(centreEmailId)) {
                return "redirect:/customer/editCustomer.htm?customerId=" + customerId + "&msg=msg.emailIdNotValidForCenter";
            } else if ((emailTypeId == 4 || emailTypeId == 7) && !CommonUtils.isValidEmailId(doctorEmailId)) {
                return "redirect:/customer/editCustomer.htm?customerId=" + customerId + "&msg=msg.emailIdNotValidForDoctor";
            }
        }
        this.emailService.sendEmail(emailBody, customer, emailTypeId, doctorId, centerId);
        return "redirect:/customer/editCustomer.htm?customerId=" + customerId + "&msg=msg.emailSentSuccessfully";
    }

    @RequestMapping(value = {"email/createEmailBody"}, method = RequestMethod.POST, params = "_cancel")
    public String sendEmailCancel(ModelMap modelMap) {

        return "customer/updateCustomer";
    }

    @RequestMapping(value = "getEmailBody.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGetEmailBody(@RequestParam(value = "customerName", defaultValue = "0") String customerName,
            @RequestParam(value = "customerId", required = true, defaultValue = "0") String customerId,
            @RequestParam(value = "emailTypeId", required = true, defaultValue = "0") String emailTypeId,
            @RequestParam(value = "centerId", defaultValue = "0") String centerId,
            @RequestParam(value = "centerName", defaultValue = "0") String centerName,
            @RequestParam(value = "centerContact", defaultValue = "0") String centerContact,
            @RequestParam(value = "doctorId", defaultValue = "0") String doctorId,
            @RequestParam(value = "doctorName", defaultValue = "0") String doctorName,
            @RequestParam(value = "appointmentDate", defaultValue = "0") String appointmentDate,
            @RequestParam(value = "mrNo", defaultValue = "0") String mrNo,
            @RequestParam(value = "phone1", defaultValue = "0") String phone1,
            @RequestParam(value = "address", defaultValue = "0") String address,
            @RequestParam(value = "cheifComplaint", defaultValue = "0") String cheifComplaint,
            @RequestParam(value = "serviceName", defaultValue = "0") String serviceName,
            @RequestParam(value = "hospitalName", defaultValue = "0") String hospitalName) {
        System.out.println("inside AJAX");
        System.out.println("hospitalName :" + hospitalName);
        int centerId1 = 0;
        int doctorId1 = 0;

        int customerId1 = Integer.parseInt(customerId);
        int emailTypeId1 = Integer.parseInt(emailTypeId);
        if (!"".equals(centerId)) {
            centerId1 = Integer.parseInt(centerId);
        }
        if (!"".equals(doctorId)) {
            doctorId1 = Integer.parseInt(doctorId);
        }
        String curUser = ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        String emailBody = this.emailService.createEmailBody(customerName,customerId1,emailTypeId1, centerId1, centerName, centerContact ,doctorId1, doctorName, appointmentDate, curUser, mrNo, phone1, address, cheifComplaint, serviceName, hospitalName);

        Gson gson = new Gson();
        String json = gson.toJson(emailBody);
        return json.toString();
    }

    @RequestMapping(value = "ajaxCallForHospitalListForEmail.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxCustomerPopulate(HttpServletRequest request) {//ajaxCallForHospitalList

        String str = request.getParameter("term");
        String json;
        List<Hospital> hospitalList = this.hospitalService.hospitalListForAutoComplete(str);
        //System.out.println("list" + hospitalList.size());
        Gson gson = new Gson();
        List list = new ArrayList();
        for (Hospital h : hospitalList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", h.getHospitalId());
            map.put("label", h.getHospitalName());
            map.put("value", h.getHospitalName());
            list.add(map);
        }
        Type typeList = new TypeToken<List>() {
        }.getType();
        json = gson.toJson(list, typeList);
        //System.out.println("json :" + json);
        return json;
    }
}
